<template>
    <el-dialog :title="dialogType == 'add' ? '新增菜单' : '编辑菜单'" v-model="dialogVisible" :before-close="handleClose"
        :close-on-click-modal="false" top="10vh" width="40%">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="上级菜单" placeholder="请选择上级菜单">
                <el-tree-select v-model="form.pid" node-key="id" :data="treeMenus" :props="defaultTreeSelectProps"
                    @node-click="handleNodeClick" filterable check-strictly clearable />
            </el-form-item>
            <el-form-item label="菜单类型:" prop="menuType">
                <el-select v-model="form.menuType" placeholder="请选择" clearable>
                    <el-option v-for="item in menuTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="权限编码:" prop="permissions">
                <el-input v-model="form.permissions" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="菜单名称:" prop="name">
                <el-input v-model="form.name" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="菜单地址:" prop="url">
                <el-input v-model="form.url" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="菜单图标:" prop="icon">
                <div class="flex-space ">
                    <el-icon size="20">
                        <component :is="form.icon" />
                    </el-icon>
                    <el-select v-model="form.icon" placeholder="请选择" clearable filterable>
                        <el-option v-for="icon in icons" :key="icon" :label="icon" :value="icon">
                            <div class="flex_between">
                                <el-icon size="20">
                                    <component :is="icon" />
                                </el-icon>
                                <span>{{ icon }}</span>
                            </div>
                        </el-option>
                    </el-select>
                </div>

            </el-form-item>
            <el-form-item label="状态:" prop="status">
                <el-switch v-model="form.status" active-text="正常" inactive-text="停用" active-value="1"
                    inactive-value="0" />
            </el-form-item>
            <el-form-item label="排序号:" prop="sort">
                <el-input-number v-model="form.sort" :min="1" :max="999" />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetClick()">重置</el-button>
            <el-button type="primary" :loading="btnLoading" @click="submitClick(formRef)">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { addMenu, updateMenu, getMenuTree } from "@/api/sys/menuApi.ts";
import { ElMessage } from 'element-plus';
import { delNullProperty } from '@/utils';
import useAppStore from '@/stores/modules/app';
import { Tree } from 'element-plus/es/components/tree-v2/src/types';
import * as iconList from "@element-plus/icons-vue";

const defaultTreeSelectProps = {
    children: 'children',
    label: 'name',
}
const icons = ref(Object.keys(iconList))
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],

    menuType: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})
const emit = defineEmits(['searchTable'])
const menuTypeOptions = useAppStore().sysDict.sys_menu_type || []

const treeMenus = ref<SysMenuEntity[]>([]);

const btnLoading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref('');
const form = ref({
    id: null,
    pid: null,
    name: '',
    url: '',
    menuType: '',
    icon: '',
    permissions: '',
    status: '1',
    sort: 999
})

const openLoad = (type: string, data: any) => {
    dialogVisible.value = true;
    dialogType.value = type;
    initTreeSelect();
    if (type == "add") {
        form.value.id = null;
        form.value.pid = null;
        form.value.name = '';
        form.value.url = '';
        form.value.menuType = '';
        form.value.icon = '';
        form.value.permissions = '';
        form.value.status = '1';
        form.value.sort = 999;

    } else {
        form.value.id = data.id;
        form.value.pid = data.pid;
        form.value.name = data.name;
        form.value.url = data.url;
        form.value.menuType = data.menuType;
        form.value.icon = data.icon;
        form.value.permissions = data.permissions;
        form.value.status = data.status;
        form.value.sort = 999;
    }
}
const initTreeSelect = async () => {
    const res = await getMenuTree();
    if (res.code == 200) {
        treeMenus.value = res.result;
        console.log(treeMenus.value)
    }
}
const submitClick = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    btnLoading.value = true;
    setTimeout(() => {
        btnLoading.value = false;
    }, 5000);
    formEl.validate(async (valid) => {
        if (valid) {
            try {
                const data = {
                    ...delNullProperty(form.value)
                }
                const res = dialogType.value == 'add' ? await addMenu(data) : await updateMenu(data)
                if (res.code == 200) {
                    btnLoading.value = false;
                    dialogVisible.value = false;
                    ElMessage.success("操作成功！");
                    emit('searchTable')
                } else {
                    ElMessage.error(res.message);
                }
            } catch (error) {
                ElMessage.error("未知错误，请联系管理员！");
            }
        } else {
            console.log('error submit!')
            btnLoading.value = false
            return false;
        }
    })
}
const resetClick = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    } else {
        form.value.id = null;
        form.value.pid = null;
        form.value.name = '';
        form.value.url = '';
        form.value.menuType = '';
        form.value.icon = '';
        form.value.permissions = '';
        form.value.status = '1';
        form.value.sort = 999;
    }
}
const handleClose = () => {
    resetClick()
    dialogType.value = '';
    dialogVisible.value = false;
    btnLoading.value = false;
}
const handleNodeClick = (data: Tree) => {
    console.log(data)
}
defineExpose({
    openLoad
})
</script>

<style lang="scss" scoped>
.flex-space {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    .el-icon {
        padding-right: 10px;
    }
}
</style>